package org.ewaf.framework.model;

import java.util.ArrayList;
import java.util.List;


/**
 * 列表查询条件的基类,分页功能的实现类
 */
public class ListModel<M> {
	
	/**
	 * 每页显示记录数,缺省每页10条
	 */
	private int pageSize=10;
	
	//--------- 输入参数 ----------
	
	/**
	 * 第几页，从1开始
	 */
	private int page = 1;
	
	
	/**
	 * 起始记录数
	 */
	private int start = 0;
	
	
	/**
	 * 排序字段名称
	 */
	private String orderBy;
	
	/**
	 * 是否降序
	 */
	private boolean desc;
	
	//--------- 输出参数 ----------
	
	/**
	 * 记录总数
	 */
	private int total;
	
	/**
	 * 查询结果集
	 */
	private List<M> result = new ArrayList<M>(1);
	

	public ListModel(int pageSize) {
		this.pageSize = pageSize;
	}
	
	public ListModel(){}
	
	public boolean isDesc() {
		return desc;
	}

	public void setDesc(boolean desc) {
		this.desc = desc;
	}

	public String getOrderBy() {
		return orderBy;
	}

	public void setOrderBy(String orderBy) {
		this.orderBy = orderBy;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page=page;
		this.start=(page-1)*pageSize;
		
	}
	
	public void setStart(int start){
		this.start=start;
		this.page=(start/pageSize)+1;
	}
	/**
	 * 0gt;pageSizlt;100
	 *@see ListModel#setPageSize(int)
	 *@return pageSize
	 * */
	public int getPageSize() {
		if(pageSize<=0||pageSize>100){
			return 10;
		}else{
			return pageSize;
		}
	}
	public void setPageSize(int pageSize){
		this.pageSize=pageSize;
	}
	public List<M> getResult() {
		return result;
	}

	public void setResult(List<M> result) {
		this.result = result;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
		
		// 调整page的实际位置
		int pageCount = getPageCount();
		if (page > pageCount) {
			page = pageCount;
		}
		
		if (page < 1) {
			page = 1;
		}
	}

	//--------- 计算属性 ----------
	
	/**
	 * 分页查询的起始记录
	 */
	public int getStart() {
		int pg = page < 1 ? 1 : page;
		return pageSize * (pg - 1);
	}
	
	/**
	 * 排序类型
	 */
	public String getOrderType() {
		return desc ? "desc" : "asc";
	}

	/**
	 * 总页数
	 */
	public int getPageCount() {
		return (total + pageSize - 1) / pageSize;
	}
	
}
